package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.model.agent.AgentCategory;
import com.zbkj.common.model.agent.AgentConfigItems;
import com.zbkj.common.model.agent.BrandAgent;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.response.*;

import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.AgentConfig;
import com.zbkj.service.dao.AgentConfigDao;
import com.zbkj.service.service.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author dazongzi
* @description AgentConfigServiceImpl 接口实现
* @date 2025-07-01
*/
@Service
public class AgentConfigServiceImpl extends ServiceImpl<AgentConfigDao, AgentConfig> implements AgentConfigService {

    @Resource
    private AgentConfigDao dao;

    @Autowired
    private AgentConfigItemsService agentConfigItemsService;

    @Autowired
    private AgentCategoryService agentCategoryService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private BrandService brandService;
    @Autowired
    private SystemAdminService systemAdminService;


    @Override
    public Boolean create(AgentConfigSaveRequest agentConfigSaveRequest) {
        // 相同的品牌商合并配置
        AgentConfig agentConfig = getAgentConfigByBrandId(agentConfigSaveRequest.getTargetBrandId());
        if (ObjectUtil.isNull(agentConfig)) {
            agentConfig = new AgentConfig();
            agentConfig.setBrandId(BrandUtil.getBrandIdByUrl());
        }else{
            agentConfigSaveRequest.setId(agentConfig.getId());
        }
        BeanUtils.copyProperties(agentConfigSaveRequest, agentConfig);
        boolean save = saveOrUpdate(agentConfig);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        // 分类数据
        addAgentItem(agentConfigSaveRequest, agentConfig.getId());
        return save;
    }

    private void addAgentItem(AgentConfigSaveRequest agentConfigSaveRequest, Integer configId) {
        int sort = 1;
        List<AgentConfigItems> agentConfigItemsList = new ArrayList<>();
        for (AgentConfigCategoryRequest agentConfigCategoryRequest : agentConfigSaveRequest.getCategoryList()) {
            if (!BooleanUtil.isTrue(agentConfigCategoryRequest.getIsSelected())) {
                continue;
            }
            AgentConfigItems agentConfigItems = new AgentConfigItems();
            BeanUtils.copyProperties(agentConfigCategoryRequest, agentConfigItems, "id");
            agentConfigItems.setId(null);
            agentConfigItems.setConfigId(configId);
            AgentCategory agentCategory = agentCategoryService.getById(agentConfigCategoryRequest.getCategoryId());
            agentConfigItems.setCategoryName(agentCategory.getCategoryName());
            agentConfigItems.setCategorySn(agentCategory.getCategorySn());
            agentConfigItems.setStatus(1);
            agentConfigItems.setSort(sort);
            agentConfigItemsList.add(agentConfigItems);
            sort += 10;
        }
        agentConfigItemsService.saveBatch(agentConfigItemsList);
    }

    private AgentConfig getAgentConfigByBrandId(Integer targetBrandId) {
        return getOne(new LambdaQueryWrapper<AgentConfig>()
                .eq(AgentConfig::getTargetBrandId, targetBrandId)
                .eq(AgentConfig::getIsDel, false)
                .eq(AgentConfig::getBrandId, BrandUtil.getBrandIdByUrl()));

    }
    @Override
    public AgentConfig getAgentConfigByTargetBrand(Integer targetBrandId) {
        return getOne(new LambdaQueryWrapper<AgentConfig>()
                .eq(AgentConfig::getTargetBrandId, targetBrandId)
                .eq(AgentConfig::getIsDel, false)
                .eq(AgentConfig::getBrandId, 0));

    }

    /**
     * 分页查询平台代理配置表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<AgentConfig>
     * @author dazongzi
     * @since 2025-07-01
     */
    @Override
    public List<AgentConfigPageDataResponse> getList(AgentConfigSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<AgentConfig> lambdaQueryWrapper = Wrappers.lambdaQuery();

        lambdaQueryWrapper.eq(AgentConfig::getIsDel, false);
        lambdaQueryWrapper.eq(AgentConfig::getBrandId, BrandUtil.getBrandIdByUrl());

        if (StrUtil.isNotBlank(request.getName())) {
            List<Integer> brandIdList = brandService.getIdsByName(request.getName());
            lambdaQueryWrapper.in(AgentConfig::getTargetBrandId, brandIdList);
        }

        lambdaQueryWrapper.orderByDesc(AgentConfig::getCreateTime);
        List<AgentConfig> agentConfigs = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<AgentConfigPageDataResponse> agentConfigResponses = new ArrayList<>();

        agentConfigs.stream().forEach(x->{
            AgentConfigPageDataResponse agentConfigResponse = new AgentConfigPageDataResponse();
            BeanUtils.copyProperties(x, agentConfigResponse);
            // 品牌商名称
            String name = brandService.getNameById(x.getTargetBrandId());
            agentConfigResponse.setBrandName(name);
            // 分类数据
            List<AgentConfigItems> agentConfigItemsList = agentConfigItemsService.getListByConfigId(x.getId());
            if (CollUtil.isNotEmpty(agentConfigItemsList)) {
                List<AgentBrandCategoryDataRespone> list = new ArrayList<>();
                for (AgentConfigItems agentConfigItems : agentConfigItemsList) {
                    AgentBrandCategoryDataRespone agentBrandCategoryDataRespone = new AgentBrandCategoryDataRespone();
                    BeanUtils.copyProperties(agentConfigItems, agentBrandCategoryDataRespone);
                    // 营业额
                    agentBrandCategoryDataRespone.setBusinessAmount(new BigDecimal("6556.60"));
                    agentBrandCategoryDataRespone.setAmount(
                            agentBrandCategoryDataRespone.getBusinessAmount()
                                    .multiply(agentBrandCategoryDataRespone.getBrokerage())
                                    .divide(new BigDecimal("100"))
                                    .setScale(2, BigDecimal.ROUND_DOWN));
                    list.add(agentBrandCategoryDataRespone);
                }
                agentConfigResponse.setCategoryList(list);
            }
            agentConfigResponses.add(agentConfigResponse);
        });
        return agentConfigResponses;
    }

    @Override
    public boolean updatePlatform(AgentConfigSaveRequest agentConfigRequest) {
        AgentConfig agentConfig = new AgentConfig();
        BeanUtils.copyProperties(agentConfigRequest, agentConfig);
        agentConfig.setId(agentConfigRequest.getId());
        updateById(agentConfig);
        // 分类数据
        agentConfigItemsService.deleteByConfigId(Arrays.asList(agentConfig.getId()));
        addAgentItem(agentConfigRequest, agentConfig.getId());
        return true;
    }

    @Override
    public AgentConfigDetailResponse getDetailById(Integer id) {
        AgentConfig agentConfig = getByIdException(id);
        AgentConfigDetailResponse response = new AgentConfigDetailResponse();
        BeanUtils.copyProperties(agentConfig, response);
        // 分类数据
        List<AgentConfigItems> agentConfigItemsList = agentConfigItemsService.getListByConfigIdPlatform(agentConfig.getId());
        // 全量分类列表
        List<AgentCategory> agentCategoryList = agentCategoryService.getListPlatform();
        List<AgentConfigCategoryResponse> categoryResponseList = new ArrayList<>();
        for (AgentCategory agentCategory : agentCategoryList) {
            AgentConfigCategoryResponse agentConfigCategoryResponse = new AgentConfigCategoryResponse();
            BeanUtils.copyProperties(agentCategory, agentConfigCategoryResponse);
            agentConfigCategoryResponse.setId(agentCategory.getId());
            agentConfigCategoryResponse.setCategoryId(agentCategory.getId());
            agentConfigCategoryResponse.setIsSelected(false);
            setIsSelected(agentConfigCategoryResponse, agentConfigItemsList);
            categoryResponseList.add(agentConfigCategoryResponse);
        }
        response.setCategoryList(categoryResponseList);
        String name = brandService.getNameById(agentConfig.getTargetBrandId());
        response.setTargetBrandName(name);
        return response;
    }

    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<AgentConfig> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(AgentConfig::getIsDel, 1);
        wrapper.in(AgentConfig::getId, idList);

        return transactionTemplate.execute(e -> {
            update(wrapper);
            agentConfigItemsService.deleteByConfigId(idList);
            return Boolean.TRUE;
        });
    }

    @Override
    public List<BrandAgentCategoryListResponse> getPlatformCategoryList() {
        // 管理员id获取品牌商id
        /*
        Integer brandId = BrandUtil.getBrandIdByUrl();
        brandId = systemAdminService.getBrandIdById(brandId);
        AgentConfig agentConfig = getOne(new LambdaQueryWrapper<AgentConfig>()
                .eq(AgentConfig::getTargetBrandId, brandId)
                .eq(AgentConfig::getBrandId, 0)
                .eq(AgentConfig::getIsDel, false));
        if (agentConfig != null) {
            // 分类
            List<AgentConfigItems> agentConfigItemsList = agentConfigItemsService.getListByConfigId(agentConfig.getId());
            if (CollUtil.isNotEmpty(agentConfigItemsList)) {
                List<BrandAgentCategoryListResponse> list = new ArrayList<>();
                agentConfigItemsList.stream().forEach(e -> {
                    BrandAgentCategoryListResponse brandAgentCategoryListResponse = new BrandAgentCategoryListResponse();
                    brandAgentCategoryListResponse.setCategoryId(e.getCategoryId());
                    AgentCategory agentCategory = agentCategoryService.getById(e.getCategoryId());
                    brandAgentCategoryListResponse.setCategorySn(agentCategory.getCategorySn());
                    brandAgentCategoryListResponse.setCategoryName(agentCategory.getCategoryName());
                    list.add(brandAgentCategoryListResponse);
                });
                return list;
            }
        }*/
        // 品牌方配置
        List<AgentCategory> agentCategoryList = agentCategoryService.getListPlatformAndBrand(BrandUtil.getBrandIdByUrl());
        if (CollUtil.isNotEmpty(agentCategoryList)) {
            List<BrandAgentCategoryListResponse> list = new ArrayList<>();
            agentCategoryList.stream().forEach(e -> {
                BrandAgentCategoryListResponse brandAgentCategoryListResponse = new BrandAgentCategoryListResponse();
                BeanUtils.copyProperties(e, brandAgentCategoryListResponse);
                brandAgentCategoryListResponse.setCategoryId(e.getId());
//                brandAgentCategoryListResponse.setCategorySn(e.getCategorySn());
//                brandAgentCategoryListResponse.setCategoryName(e.getCategoryName());
                list.add(brandAgentCategoryListResponse);
            });
            return list;
        }
        return null;
    }

    @Override
    public AgentConfigItems getPlatformCategotysBrokerage(Integer agentConfigCategoryId) {
        Integer brandId = BrandUtil.getBrandIdByUrl();
        brandId = systemAdminService.getBrandIdById(brandId);
        AgentConfig agentConfig = getOne(new LambdaQueryWrapper<AgentConfig>()
                .eq(AgentConfig::getTargetBrandId, brandId)
                .eq(AgentConfig::getStatus, 1)
                .eq(AgentConfig::getIsDel, false));
        if (agentConfig != null) {
            // 分类
            return agentConfigItemsService.getByConfigId(agentConfig.getId(), agentConfigCategoryId);
        }
        return null;
    }

    @Override
    public boolean updateStatus(AgentStatusRequest request) {
        AgentConfig agentConfig = getById(request.getId());
        if (ObjectUtil.isNull(agentConfig)) {
            throw new AppException("代理设置不存在");
        }
        if (agentConfig.getStatus().equals(request.getStatus())) {
            return true;
        }
        agentConfig.setStatus(request.getStatus());
        return updateById(agentConfig);
    }

    private void setIsSelected(AgentConfigCategoryResponse agentConfigCategoryResponse, List<AgentConfigItems> agentConfigItemsList) {
        agentConfigItemsList.stream().forEach(e -> {
            if (e.getCategoryId().equals(agentConfigCategoryResponse.getCategoryId())) {
                agentConfigCategoryResponse.setIsSelected(true);
                agentConfigCategoryResponse.setBrokerage(e.getBrokerage());
            }
        });
    }

    private AgentConfig getByIdException(Integer jobId) {
        AgentConfig agentConfig = getById(jobId);
        if (ObjectUtil.isNull(agentConfig) || BooleanUtil.isTrue(agentConfig.getIsDel())) {
            throw new AppException("代理设置不存在");
        }
        return agentConfig;
    }

}

